package org.jeecg.modules.demo.integrityArchive.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.SelectTreeModel;
import org.jeecg.modules.demo.hdLevelConfiguration.entity.HdLevelConfiguration;
import org.jeecg.modules.demo.hdLevelConfiguration.service.IHdLevelConfigurationService;
import org.jeecg.modules.demo.integrityArchive.entity.IntegrityArchive;
import org.jeecg.modules.demo.integrityArchive.service.IIntegrityArchiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

 /**
 * @Description: 廉洁档案表
 * @Author: jeecg-boot
 * @Date:   2025-04-08
 * @Version: V1.0
 */
@Tag(name = "廉洁档案表")
@RestController
@RequestMapping("/integrityArchive/integrityArchive")
@Slf4j
public class IntegrityArchiveController extends JeecgController<IntegrityArchive, IIntegrityArchiveService> {
	 @Autowired
	 private IIntegrityArchiveService integrityArchiveService;

	 @Autowired
	 private IHdLevelConfigurationService hdLevelConfigurationService;

	 /**
	  * 分页列表查询
	  *
	  * @param integrityArchive
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 //@AutoLog(value = "廉洁档案表-分页列表查询")
	 @Operation(summary = "廉洁档案表-分页列表查询", description = "廉洁档案表-分页列表查询")
	 @GetMapping(value = "/list")
	 public Result<IPage<IntegrityArchive>> queryPageList(IntegrityArchive integrityArchive,
														  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
														  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
														  HttpServletRequest req) {
		 pageSize = 8;
		 QueryWrapper<IntegrityArchive> queryWrapper = QueryGenerator.initQueryWrapper(integrityArchive, req.getParameterMap());
		 Page<IntegrityArchive> page = new Page<IntegrityArchive>(pageNo, pageSize);
		 IPage<IntegrityArchive> pageList = integrityArchiveService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	 @Operation(summary = "廉洁档案表-分页列表查询", description = "廉洁档案表-分页列表查询")
	 @GetMapping(value = "/childList")
	 public Result<IPage<IntegrityArchive>> childList(IntegrityArchive integrityArchive,
													  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
													  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
													  HttpServletRequest req) {
		 pageSize = 8;
		 QueryWrapper<IntegrityArchive> queryWrapper = QueryGenerator.initQueryWrapper(integrityArchive, req.getParameterMap());
		 queryWrapper.orderByDesc("create_time");
		 List<IntegrityArchive> list = integrityArchiveService.list(queryWrapper);
		 IPage<IntegrityArchive> pageList = new Page<>(1, 10000, list.size());
		 pageList.setRecords(list);
		 return Result.OK(pageList);
	 }

	 @Operation(summary = "获取上一级文件夹", description = "获取上一级文件夹")
	 @GetMapping(value = "/rootList")
	 public Result<List<IntegrityArchive>> queryPageList1(IntegrityArchive integrityArchive,
														  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
														  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
														  HttpServletRequest req) {
		 //获取父id
		 String parentId = integrityArchive.getPid();
		 IntegrityArchive lastFol = integrityArchiveService.getById(parentId);
		 String pid = null;
		 //删除后，防止空指针异常
		 if (lastFol == null){
			 pid = "0";
		 }else {
			 pid = lastFol.getPid();
		 }
		 // 拼接pid的条件
		 QueryWrapper<IntegrityArchive> queryWrapper = QueryGenerator.initQueryWrapper(integrityArchive, req.getParameterMap());
		 queryWrapper.lambda().eq(IntegrityArchive::getPid,pid);
		 List<IntegrityArchive> list = integrityArchiveService.list(queryWrapper);
		 System.out.println("list = " + list);
//		IPage<CesFolder> pageList = cesFolderService.page(page, queryWrapper);
		 return Result.OK(list);
	 }

	 @AutoLog(value = "文件上传")
	 @Operation(summary = "文件上传", description = "文件上传")
	 @PostMapping(value = "/uploadfile")
	 public Result<String> uploadfile(@RequestBody IntegrityArchive integrityArchive) throws Exception {
		 String stringResult = integrityArchiveService.uploadSceneFile(integrityArchive);
		 //获取文件页数
		 return Result.OK(stringResult);
	 }


	 /**
	  * 【vue3专用】加载一级节点/如果是同步 则所有数据
	  *
	  * @param async
	  * @param pcode
	  * @return
	  */
	 @RequestMapping(value = "/loadTreeRoot", method = RequestMethod.GET)
	 public Result<List<SelectTreeModel>> loadTreeRoot(@RequestParam(name = "async") Boolean async, @RequestParam(name = "pcode") String pcode) {
		 Result<List<SelectTreeModel>> result = new Result<>();
		 try {
			 List<SelectTreeModel> ls = integrityArchiveService.queryListByCode(pcode);
			 if (!async) {
				 loadAllChildren(ls);
			 }
			 result.setResult(ls);
			 result.setSuccess(true);
		 } catch (Exception e) {
			 e.printStackTrace();
			 result.setMessage(e.getMessage());
			 result.setSuccess(false);
		 }
		 return result;
	 }

	 /**
	  * 【vue3专用】递归求子节点 同步加载用到
	  *
	  * @param ls
	  */
	 private void loadAllChildren(List<SelectTreeModel> ls) {
		 for (SelectTreeModel tsm : ls) {
			 List<SelectTreeModel> temp = integrityArchiveService.queryListByPid(tsm.getKey());
			 if (temp != null && temp.size() > 0) {
				 tsm.setChildren(temp);
				 loadAllChildren(temp);
			 }
		 }
	 }

	/**
	 *   添加
	 *
	 * @param integrityArchive
	 * @return
	 */
	@AutoLog(value = "廉洁档案表-添加")
	@Operation(summary = "廉洁档案表-添加", description = "廉洁档案表-添加")
	@RequiresPermissions("integrityArchive:integrity_archive:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody IntegrityArchive integrityArchive) {
		integrityArchiveService.addIntegrityArchive(integrityArchive);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param integrityArchive
	 * @return
	 */
	@AutoLog(value = "廉洁档案表-编辑")
	@Operation(summary = "廉洁档案表-编辑", description = "廉洁档案表-编辑")
	@RequiresPermissions("integrityArchive:integrity_archive:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody IntegrityArchive integrityArchive) {
		String pid = integrityArchive.getPid();
		if (IIntegrityArchiveService.ROOT_PID_VALUE.equals(pid)) {
			integrityArchiveService.updateById(integrityArchive);
			//根据pid得到list<IntegrityArchive>
			List<IntegrityArchive> integrityArchives = integrityArchiveService.queryByPid(integrityArchive.getId());
			for (IntegrityArchive integrityArchive1 : integrityArchives) {
				integrityArchive1.setPosition(integrityArchive.getPosition());
				integrityArchive1.setName(integrityArchive.getName());
				integrityArchive1.setPosition(integrityArchive.getPosition());
				integrityArchive1.setLevel(integrityArchive.getLevel());
				integrityArchive1.setDepartment(integrityArchive.getDepartment());
				integrityArchiveService.updateById(integrityArchive1);
			}
		}
//        integrityArchiveService.updateById(integrityArchive);
        return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "廉洁档案表-通过id删除")
	@Operation(summary = "廉洁档案表-通过id删除", description = "廉洁档案表-通过id删除")
	@RequiresPermissions("integrityArchive:integrity_archive:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		integrityArchiveService.removeIntegrityArchive(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "廉洁档案表-批量删除")
	@Operation(summary = "廉洁档案表-批量删除", description = "廉洁档案表-批量删除")
	@RequiresPermissions("integrityArchive:integrity_archive:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.integrityArchiveService.removeByIds(Arrays.asList(ids.split(",")));
		this.integrityArchiveService.removeAll(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "廉洁档案表-通过id查询")
	@Operation(summary = "廉洁档案表-通过id查询", description = "廉洁档案表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<IntegrityArchive> queryById(@RequestParam(name="id",required=true) String id) {
		IntegrityArchive integrityArchive = integrityArchiveService.getById(id);
		if(integrityArchive==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(integrityArchive);
	}

	 /**
	  * 通过职级查询人数
	  *
	  * @param
	  * @return
	  */
	 @Operation(summary = "廉洁档案表-通过职级查询人数", description = "廉洁档案表-通过职级查询人数")
	 @GetMapping(value = "/getSumByLevel")
	 public Result<Map<String,Long>> getSumByLevel() {
		 Map<String,Long> result = new HashMap<>();
		 List<HdLevelConfiguration> list = hdLevelConfigurationService.list();
		 for (HdLevelConfiguration hdLevelConfiguration : list) {
			 LambdaQueryWrapper<IntegrityArchive> query = new LambdaQueryWrapper<>();
			 query.eq(IntegrityArchive::getLevel,hdLevelConfiguration.getLevel());
			 Long count = integrityArchiveService.count(query);
			 result.put(hdLevelConfiguration.getLevel(),count);
		 }
		 return Result.OK(result);
	 }

    /**
    * 导出excel
    *
    * @param request
    * @param integrityArchive
    */
    @RequiresPermissions("integrityArchive:integrity_archive:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, IntegrityArchive integrityArchive) {
        return super.exportXls(request, integrityArchive, IntegrityArchive.class, "廉洁档案表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("integrityArchive:integrity_archive:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, IntegrityArchive.class);
    }

}
